import json
import os
import re


from bs4 import BeautifulSoup
import requests
hds={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"}
askurl=r"https://prts.wiki/api.php?action=parse&format=json&page=PRTS%3A%E6%96%87%E4%BB%B6%E4%B8%80%E8%A7%88%2F%E5%B9%B2%E5%91%98%E7%9A%AE%E8%82%A4"
findurlhd=r"https://prts.wiki/w/%E6%96%87%E4%BB%B6:"
resp=requests.get(askurl,headers=hds)#发送request请求获取数据
html=resp.text
# 解析 JSON 字符串为 Python 字典
data = json.loads(html)
# 提取 image 部分
image_data = data["parse"]["images"]
# print(image_data)
# 使用正则表达式匹配类似于“立绘_XXX_skin1.png”的字符串
pattern = r"立绘_\w+_skin1\.png"
# matches = re.findall(pattern,image_data)
# matches = [img for img in image_data if re.search(pattern,img)]
for img in image_data:
    if re.search(pattern, img):
        page_url=findurlhd+img
        # page_url = os.path.basename(findurlhd+img)
        # print(page_url)
        # 创建 BeautifulSoup 对象
        resp1=requests.get(page_url,headers=hds)
        html1=resp1.text
        soup1 = BeautifulSoup(html1, 'html.parser')
        # 查找包含“原始文件”文本的 <a> 元素
        target_link = soup1.find('a', text='原始文件')
        # # 获取该元素的 href 属性值
        if target_link:
            img_url = target_link.get('href')
            print(img_url)
            img_name="C:\\Users\\22058\\Pictures\\Arkinights\\"+img  
            with open(img_name, "wb") as img_file:
                img_file.write(requests.get(img_url).content)
            print(f"已下载图片：{img_name}")

# print("图片下载完成！")
# 输出匹配到的字符串